<?php
namespace app\model;

use think\Model;

use think\facade\Db;

class CustomerModel extends Model
{

    public static function get_list( $filter ){

        $uniacid = current_uni_account();
        $where_arr = [];
        $where_arr[] = ' c.uniacid=' . $uniacid;
        if( !empty($filter['name']) ){
            $where_arr[] = ' c.name like "%' . $filter['name'] . '%"';
        }

        if( isset($filter['status']) ){
            $where_arr[] = ' c.status = "' . $filter['status'] . '"';
        }

        if( !empty($filter['telephone']) ){
            $where_arr[] = ' c.telephone like "%' . $filter['telephone'] . '%"';
        }

        if( !empty($filter['customer_group_id']) ){
            $where_arr[] = ' c.customer_group_id = "' . $filter['customer_group_id'] . '"';
        }

        $where_str = '';
        if( !empty( $where_arr ) ){
            $where_str = ' where ' . join(' and ', $where_arr );
        }

        $sql = 'select c.*, cg.name as customer_group '
            . ' from sh_customer c '
            . ' left join sh_customer_group cg on c.customer_group_id=cg.id '
            . $where_str
            . ' order by c.create_time desc '
        ;

        $total_sql = 'select count(c.id) as total'
        . ' from sh_customer c '
        . $where_str ; 

        $page_size = isset($_GET['page_size'])? intval($_GET['page_size']):15;
        $page = isset($_GET['page'])? intval($_GET['page']):1;
        $sql .= ' limit ' . ($page - 1) * $page_size . ',' . $page_size;
    
        return [
            'list'  => Db::query( $sql ),
            'page'  =>[
                'total'     => Db::query( $total_sql )[0]['total'],
                'page_size' => $page_size,
                'page'      => $page,
            ]

        ];

    }


    public static function single( $customer_id ){

        $sql = 'select * from sh_customer where id=' . $customer_id;

        // return pdo_fetch( $sql );
        return Db::query( $sql )[0];
    }

    public static function edit( $id, $data ){

        $sql = 'update sh_customer set customer_group_id= '
            . $data['customer_group_id']
            . ', remark= "' . $data['remark'] . '"'
            . ' where id=' . $id;

        // return pdo_query( $sql );
        return Db::execute( $sql );
    }

}